package com.ruoyi.api;
import com.ruoyi.biz.domain.FrontUser;
import com.ruoyi.biz.mapper.FrontUserMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.RegisterRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
@RequestMapping("/api/register")
@Transactional(rollbackFor = Exception.class)
public class RegisterController {
    @Resource
    private FrontUserMapper frontUserMapper;

    @PostMapping
    public AjaxResult register(@RequestBody RegisterRequest registerRequest){
        log.info("用户注册，{}",registerRequest);
        //校验注册信息
        String username = registerRequest.getUsername();
        String phone = registerRequest.getPhone();
        String account = registerRequest.getAccount();
        String password = registerRequest.getPassword();
        String confirmPassword = registerRequest.getConfirmPassword();
        // 用户名不能为空 且在1~7个字符之间
        if(StringUtils.isEmpty(username) || username.length() > 7){
            throw new BaseException("用户名不能为空 且在1~7个字符之间");
        }
        // 手机号不能为空，且在11位
        if(StringUtils.isEmpty(phone) || phone.length() != 11){
            throw new BaseException("不符合手机号码格式");
        }

        // 账号不能为空，且在6~18个字符之间
        if(StringUtils.isEmpty(account) || account.length() < 6 || account.length() > 18){
            throw new BaseException("账号不能为空，且在6~18个字符之间");
        }

        // 密码不能为空，且在6~18个字符之间
        if(StringUtils.isEmpty(password) || password.length() < 6 || password.length() > 18){
            throw new BaseException("密码不能为空，且在6~18个字符之间");
        }

        // 确认密码不能为空，且与密码一致
        if(!confirmPassword.equals(password)){
            throw new BaseException("两次密码不一致");
        }

        // 判断账号是否已经存在
        FrontUser frontUser = frontUserMapper.selectByAccount(account);
        if(ObjectUtils.isNotEmpty(frontUser)){
            throw new BaseException("账号已经存在");
        }

        // 注册
        frontUserMapper.register(username,password,account,phone);

        return AjaxResult.success();
    }

}
